package com.wxc.config.shiro;

import com.wxc.utils.token.JwtTokenUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * @author wxc
 * @date 2021年10月12日 18:39
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 拿到第一个 底层: iterator().next();
        String token = (String) principals.getPrimaryPrincipal();
        // TODO 查询用户的权限列表
        // TODO 把权限列表添加到info对象中
        String id = JwtTokenUtil.getUserId(token);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        // MOCK数据
        HashSet<String> roles = new HashSet<>();
        // set.add("admin");
        roles.add("guest");
        authorizationInfo.setRoles(roles);

        HashSet<String> permissions = new HashSet<>();
        // set.add("admin");
        permissions.add("sys:user:list");
        authorizationInfo.setStringPermissions(permissions);

        return authorizationInfo;
    }

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
        // TODO 查数据库得到这个用户的账号密码
        return new SimpleAuthenticationInfo(token.getPrincipal(),token.getCredentials(),getName());
    }
}
